<template>
  <div class="dialog">
    <el-dialog
      :title="title"
      :visible.sync="visible"
      :close-on-click-modal="false"
      width="65%"
    >
      <el-form
        :model="createForm"
        style="padding-right: 20px"
        label-width="120px"
        label-suffix=":"
        :rules="rules"
        ref="createForm"
      >
        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="门店图片" prop="images">
              <el-upload
                action="#"
                class="upload-demo"
                ref="upload"
                list-type="picture-card"
                :file-list="fileList"
                :disabled="!isupload"
                accept="png,jpg"
                :http-request="uploadActionF"
                :limit="3"
                :on-exceed="handleExceed"
              >
                <!-- @change="fileChange":on-change="fileChange" :before-remove="beforeRemove"-->

                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                      v-if="!undisabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <!-- <el-upload  action list-type="picture" :file-list="fileList"
                  :on-change="fileChange" :disabled="!isupload " accept="png,jpg" :http-request="uploadActionF"
                  :before-remove="beforeRemove">
                  <img v-if="createForm.images" :src="createForm.images" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="门店名称" prop="orgName">
              <el-input
                v-model.trim="createForm.orgName"
                placeholder="请输入门店名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="isEdit">
            <el-form-item label="管理员账号" prop="managerAccount">
              <el-input
                v-model.trim="createForm.managerAccount"
                placeholder="请输入管理员账号"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="是否为主门店" prop="isManager">
              <el-select
                v-model="createForm.isManager"
                placeholder="请选择"
                style="width: 100%"
                :disabled="isEdit"
              >
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="上级门店"
              prop="parentId"
              v-if="createForm.isManager != '1'"
            >
              <el-select
                v-model="createForm.parentId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in storeList"
                  :key="item.id"
                  :label="item.orgName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所属区域" prop="regionCodePath">
              <el-cascader
                :key="resetCascader"
                ref="regionCascader"
                v-model="createForm.regionCodePath"
                :props="props"
                @change="initSupplierList"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model.trim="createForm.address"
                placeholder="请输入详细地址"
                style="width: calc(100% - 100px)"
              ></el-input>
              <el-button
                type="primary"
                @click="choosePoint()"
                style="width: 100px"
                >选择定位</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="关联经销商" prop="supplierId">
               <el-select
                v-model="createForm.supplierId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :label="item.supplierName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contacts">
              <el-input
                v-model.trim="createForm.contacts"
                placeholder="请输入联系人"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phoneNum">
              <el-input
                v-model.trim="createForm.phoneNum"
                placeholder="请输入联系电话"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input
                v-model.trim="createForm.email"
                placeholder="请输入电子邮箱"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务范围" prop="serviceScopeList">
              <el-select
                v-model="createForm.serviceScopeList"
                placeholder="请选择服务范围"
                multiple
                style="width: 100%"
              >
                <el-option
                  v-for="item in themeTypeList"
                  :key="item.dictItemCode"
                  :label="item.dictItemName"
                  :value="item.dictItemCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="银行账号" prop="accountNumber">
              <el-input
                v-model.trim="createForm.accountNumber"
                placeholder="请输入银行账号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户行" prop="bankName">
              <el-input
                v-model.trim="createForm.bankName"
                placeholder="请输入开户行"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="纳税人识别号" prop="taxNum">
              <el-input
                v-model.trim="createForm.taxNum"
                placeholder="请输入纳税人识别号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率" prop="taxRate">
              <el-input
                v-model.trim="createForm.taxRate"
                placeholder="请输入税率"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input
                v-model.trim="createForm.description"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeNetWorker()">关 闭</el-button>
        <el-button type="primary" @click="confirmData('createForm')"
          >保 存</el-button
        >
      </div>
      <store-map-dialog ref="storeMap" @ok="choosePointOk"></store-map-dialog>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios'
import COS from 'cos-js-sdk-v5'
import StoreMapDialog from './StoreMapDialog'
import { getDictionaryItemMap } from '@/api/common'
import {
  sysRegionListByParentCode,
  sysOrganizationAdd,
  sysOrganizationUpdate,
  sysOrganizationListForSelect,
  getSupplierListByRegion
} from '@/api/index'

const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    let reg = new RegExp('\\\\', 'g')
    path = path.replace(reg, '/')
  }
  return path.substring(path.lastIndexOf('/') + 1)
}
export default {
  name: 'StoreDialog',
  components: {
    StoreMapDialog
  },
  data() {
    return {
      imagesObj: '',
      picUrl: false,
      dialogImageUrl: '',
      dialogVisible: false,
      undisabled: false,
      fileList: [],
      isupload: true,
      title: '',
      isEdit: false,
      visible: false,
      createForm: {
        position: '',
        address: '',
        images: '',
        supplierId:""
      },
      supplierList:[],
      storeList: [],
      themeTypeList: [],
      defaultProps: {
        children: 'children',
        label: 'resourceName'
      },
      resetCascader: 0,
      props: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          setTimeout(async () => {
            const res = await this.getTreeByParentCode(node)
            return resolve(res)
          })
        }
      },
      rules: {
        orgName: [
          { required: true, message: '请输入门店名称', trigger: 'blur' }
          // { max: 20, message: "字数不超过20", trigger: "blur" },
        ],
        isManager: [
          { required: true, message: '请选择是否为主门店', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择上级门店', trigger: 'blur' }
        ],
        regionCodePath: [
          { required: true, message: '请选择所属区域', trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phoneNum: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        serviceScopeList: [
          { required: true, message: '请选择服务范围', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    imagesObj(val) {
      if (val instanceof Array) {
        this.initFileList(val.join(','))
      } else {
        this.initFileList(val)
      }
    },
  },
  created() {},
  mounted() {},
  methods: {
    add() {
      this.title = '新增'
      this.isEdit = false
      this.createForm = {
        supplierId:""
      }
      this.imagesObj = ''
      this.initTree()
      this.visible = true
    },
    edit(val) {
      this.title = '编辑'
      this.isEdit = true
      this.createForm = Object.assign({}, val);
      this.createForm.supplierId = Number(this.createForm.supplierId )
      this.initSupplierList(this.createForm.regionCodePath)
      this.imagesObj = this.createForm.images ? this.createForm.images : ''
      if (this.createForm.serviceScope) {
        this.createForm.serviceScopeList =
          this.createForm.serviceScope.split(',')
      }
      this.initTree()
      this.visible = true
      this.resetCascader++
    },
    initTree() {
      sysOrganizationListForSelect({}).then((res) => {
        if (res.data.code == 0) {
          this.storeList = res.data.data
        }
      })
      getDictionaryItemMap({ codeArr: 'themeType' }).then((res) => {
        let data = res.data
        if (data && data.code == 0) {
          this.themeTypeList = data.data.themeType
        }
      })
    },
    getTreeByParentCode(node) {
      return new Promise((resolve, reject) => {
        let params = {}
        if (node.data) {
          params = { parentCode: node.data.value }
        }
        sysRegionListByParentCode(params).then((res) => {
          if (res.data.code == 0) {
            const nodes = Array.from(res.data.data).map((item) => ({
              value: item.code,
              label: item.name,
              leaf: item.type == 'street'
            }))
            resolve(nodes)
          }
        })
      })
    },
    choosePoint() {
      let region = ''
      if (this.$refs['regionCascader'].getCheckedNodes()[0]) {
        region = this.$refs['regionCascader']
          .getCheckedNodes()[0]
          .pathLabels.join(',')
      }
      this.$refs.storeMap.choose(region, this.createForm)
    },
    choosePointOk(center, address) {
      // this.createForm.position = center.lng + "," + center.lat;
      // this.createForm.address = address;
      this.$set(this.createForm, 'position', center.lng + ',' + center.lat)
      this.$set(this.createForm, 'address', address)
    },
    confirmData(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          this.createForm.orgType = '1'
          this.createForm.regionCode =
            this.createForm.regionCodePath[
              this.createForm.regionCodePath.length - 1
            ]
          this.createForm.serviceScope =
            this.createForm.serviceScopeList.join(',')
          this.createForm.images = this.imagesObj
          // this.createForm.detail = JSON.parse(JSON.stringify(this.createForm))
          if (this.createForm.id) {
            sysOrganizationUpdate(this.createForm).then((res) => {
              const data = res.data
              if (data.code == 0) {
                this.$message.success('修改成功')
                this.$emit('ok')
                this.closeNetWorker()
              } else {
                this.$message.error(data.data || '修改失败')
              }
            })
          } else {
            sysOrganizationAdd(this.createForm).then((res) => {
              const data = res.data
              if (data.code == 0) {
                this.$message.success('新增成功')
                this.$emit('ok')
                this.closeNetWorker()
              } else {
                this.$message.error(data.data || '新增失败')
              }
            })
          }
        }
      })
    },
    closeNetWorker() {
      this.createForm = {}
      this.visible = false
    },
    /**
     * 上传文件前
     */
    beforeRemove(file, fileList) {
      this.fileList = []
    },
    uploadActionF(e) {
      let that = this
      let file = e.file
      let name =
        'images/store/' + e.file.uid + '_' + encodeURIComponent(e.file.name)
      var cos = new COS({
        getAuthorization: function (options, callback) {
          // 初始化时不会调用，只有调用 cos 方法（例如 cos.putObject）时才会进入
          // 异步获取临时密钥
          axios
            .get(
              window.ipConfigUrl.cosUrl,
              {
                params: {
                  prefix: 'images',
                  type: 'putObject',
                  bucketName: window.ipConfigUrl.cosBucket
                }
              }
            )
            .then((res) => {
              if (res.data.code == 0) {
                var data = res.data.data
                console.log('数据：', data)
                callback({
                  TmpSecretId: data.tmpSecretId,
                  TmpSecretKey: data.tmpSecretKey,
                  SecurityToken: data.sessionToken,
                  // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                  StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                  ExpiredTime: data.expiredTime // 时间戳，单位秒，如：1580000000              // 临时密钥失效时间戳，是申请临时密钥时，时间戳加 durationSeconds
                })
              }
            })
        }
      })
      cos.putObject(
        {
          Bucket: window.ipConfigUrl.cosBucket /* 填入您自己的存储桶，必须字段 */,
          Region:  window.ipConfigUrl.cosRegion /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          Body: file /* 必须 */
        },
        function (err, data) {
          if (data && data.statusCode == 200) {
            that.imagesObj = that.imagesObj == ""
              ? 'images/store' + data.Location.split('store')[1] :  (that.imagesObj +
                ',' +
                'images/store' +
                data.Location.split('store')[1])
            e.onSuccess(JSON.stringify(data), file)
          } else {
            e.onError(err, e.file)
          }
        }
      )
    },
    initFileList(paths) {
      if (!paths || paths.length == 0) {
        this.fileList = []
        this.picUrl = false
        return
      }
      this.picUrl = true
      let fileList = []
      let arr = paths.split(',')
      var cos = new COS({
        getAuthorization: function (options, callback) {
          // 初始化时不会调用，只有调用 cos 方法（例如 cos.putObject）时才会进入
          // 异步获取临时密钥
          axios
            .get(
               window.ipConfigUrl.cosUrl,
              {
                params: {
                  prefix: 'images',
                  type: 'getObject',
                  bucketName: window.ipConfigUrl.cosBucket,
                }
              }
            )
            .then((res) => {
              if (res.data.code == 0) {
                var data = res.data.data
                console.log('数据：', data)
                callback({
                  TmpSecretId: data.tmpSecretId,
                  TmpSecretKey: data.tmpSecretKey,
                  SecurityToken: data.sessionToken,
                  // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                  StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                  ExpiredTime: data.expiredTime // 时间戳，单位秒，如：1580000000              // 临时密钥失效时间戳，是申请临时密钥时，时间戳加 durationSeconds
                })
              }
            })
        }
      })
      for (var a = 0; a < arr.length; a++) {
        let path = decodeURIComponent(arr[a])
        if (path) {
          cos.getObjectUrl(
            {
              Bucket: window.ipConfigUrl.cosBucket /* 填入您自己的存储桶，必须字段 */,
              Region:
                window.ipConfigUrl.cosRegion /* 存储桶所在地域，例如ap-beijing，必须字段 */,
              Key: path /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
              Sign: true,
              onProgress: function (progressData) {
                console.log(JSON.stringify(progressData))
              }
            },
            function (err, data) {
              fileList.push({
                uid: uidGenerator(),
                name: getFileName(path),
                status: 'success',
                url: data.Url,
                response: {
                  code: 'history',
                  data: path,
                  Location: path
                }
              })
            }
          )
        }
      }
      this.fileList = fileList
    },
    handleRemove(file) {
      //如有需要新增 删除逻辑
      let index = "",fileLists = JSON.parse(JSON.stringify(this.fileList)),imgs=""
      fileLists.map((item,i)=>{
        if(item.uid == file.uid){
          index = i
        }
      })
      fileLists.splice(index, 1);
      fileLists.map(item=>{
        imgs = imgs =="" ? encodeURIComponent(item.response.Location) : (imgs + ','+ encodeURIComponent(item.response.Location))
      })
      // this.fileList = fileLists
      this.imagesObj = imgs
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制只能上传3张图片`);
    },
    initSupplierList(el){
      let data = {
          regionCode: el[0]
      }
      getSupplierListByRegion(data).then(res=>{
         const { code = undefined, data = []} = res.data;
         if(!code){
          this.supplierList = data;
          let ids = data.map(item=>{
            return item.id
          })
          if(ids.indexOf(this.createForm.supplierId) == -1){
            this.createForm.supplierId = ""
          }
         }
      })
    }
  }
}
</script>
<style scoped lang="less">
.content {
  height: 400px;
  overflow: auto;
}
.pictu {
  ::v-deep .el-upload--picture {
    width: 100px !important;
    height: 100px !important;
    line-height: 100px !important;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
}
</style>
